﻿import kliment.controls.ControlsAbstract;
import kliment.display.MCC;
import kliment.math.Calc;
import mx.utils.Delegate;

/**
 * ...
 * @author	Kliment
 * @version	1.1.4
 */
class kliment.effect.Wheel extends ControlsAbstract {
	private var _360:Number = Math.PI * 2;
	private var _slope:Number = 4;
	private var _target_mc:MovieClip;
	private var _elements:Array;
	private var _clocker:MovieClip;
	private var _center_mc:MovieClip;
	private var _enable:Boolean = true;
	private var _cosX:Number;
	private var _sinX:Number;
	private var _speedX:Number;
	private var _speedY:Number;
	private var _scale:Number;
	private var _yI:Number;
	
	public var ratioX:Number = .5;
	public var ratioY:Number = .08;
	public var maxPitch:Number = 20;
	public var minPitch:Number = -10;
	public var deltaScale:Number = 100;
	public var radiusZ:Number = 50;
	public var radiusX:Number;
	
	public var centerX:Number;
	public var centerY:Number;
	
	public var onRender:Function = function(target_mc:MovieClip, value:Number):Void {}
	
	public function Wheel(target_mc:MovieClip, radiusX:Number) {
		_target_mc = target_mc;
		_clocker = MCC.create();
		this.radiusX = radiusX;
		centerX = radiusX;
		centerY = radiusX;
		_init();
	}
	
	private function _init():Void {
		_elements = new Array();
		enable = true;
	}
	
	public function set enable(value:Boolean):Void {
		if (value) {
			_clocker.onEnterFrame = Delegate.create(this, _moveHandler);
		} else {
			_clocker.onEnterFrame = null;
		}
		super.enable = value;
	}
	
	private function _moveHandler():Void {
		var length:Number = _elements.length;
		_speedX = (_target_mc._xmouse - centerX) / (radiusX * length / ratioX);
		_speedY = (_target_mc._ymouse - centerY) * ratioY;
		
		_speedY = Calc.inInterval(-maxPitch, -minPitch, _speedY);
		
		for (var i:Number = 0; i < length; ++i ) {
			var item_mc:MovieClip = _elements[i];
			item_mc.x += _speedX;
			_cosX = Math.cos(item_mc.x);
			_sinX = Math.sin(item_mc.x);
			_scale = _sinX * radiusZ + deltaScale;
			item_mc._x = _cosX * radiusX + centerX;
			item_mc._xscale = _scale;
			item_mc._yscale = _scale;
			
			var zFactor:Number = (_sinX + 1) * 50;
			item_mc._y = (-_sinX * radiusZ * _speedY / _slope + centerY);
			item_mc.swapDepths(zFactor >> 0);
			onRender(item_mc, zFactor);
		}
		
		_center_mc.swapDepths(50);
	}
	
	public function addMovieClip(target_mc:MovieClip):Void {
		_elements.push(target_mc);
		_reCalcPositions();
	}
	
	public function set center_mc(value:MovieClip):Void {
		_center_mc = value;
	}
	
	private function _reCalcPositions():Void {
		var length:Number = _elements.length;
		for (var i:Number = 0; i < length; ++i ) {
			var item_mc:MovieClip = _elements[i];
			item_mc.x = i / length * _360;
		}
	}
	
	public function remove():Void {
		MCC.remove(_clocker);
		delete this;
	}
	
}